<template>
  <div class="app-container">
    <el-row>
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :inline="true" v-show="showSearch" label-width="140px" :label-position="isPhone ? 'top' : 'left'">
          <el-form-item label="姓名" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入姓名"
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="学校" prop="trainUniversity">
            <el-select
              v-model="queryParams.trainUniversity"
              placeholder="请选择学校"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="dict in university"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="专业" prop="trainMajor">
            <el-input
              v-model="queryParams.trainMajor"
              placeholder="请输入专业"
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="培养单位" prop="trainDeptName">
            <el-input
              v-model="queryParams.trainDeptName"
              placeholder="请输入培养单位"
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="入企实践开始时间" prop="practiceStartYear">
            <el-select
              v-model="queryParams.practiceStartYear"
              placeholder="请选择年份"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="year in yearOptions"
                :key="year"
                :label="year + '年'"
                :value="year"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="handleGetList"
            :columns="columns"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="list"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="姓名"
            align="center"
            key="nickName"
            prop="nickName"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
            width="100"
          />
          <el-table-column
            label="学校"
            align="center"
            key="trainUniversity"
            prop="trainUniversity"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
            width="150"
          >
            <template #default="scope">
              {{ getUniversityText(scope.row.trainUniversity) }}
            </template>
          </el-table-column>
          <el-table-column
            label="专业"
            align="center"
            key="trainMajor"
            prop="trainMajor"
            v-if="columns[3].visible"
            :show-overflow-tooltip="true"
            width="150"
          />
          <el-table-column
            label="培养单位"
            align="center"
            key="trainDeptName"
            prop="trainDeptName"
            v-if="columns[4].visible"
            :show-overflow-tooltip="true"
            width="150"
          />
          <el-table-column
            label="入企时间"
            align="center"
            key="aa1"
            prop="aa1"
            v-if="columns[5].visible"
            :show-overflow-tooltip="true"
            width="150"
          />
          <el-table-column
            label="月度计划"
            align="center"
            key="monthlyPlan"
            v-if="columns[6].visible"
            :show-overflow-tooltip="true"
          >
            <template #default="scope">
              {{ scope.row.progressDetails.length }}个计划
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="150"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-tooltip content="详情" placement="top">
                <el-button
                  link
                  type="info"
                  icon="View"
                  @click="handleDetail(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="修改" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                  v-hasRole="['admin', 'student']"
                ></el-button>
              </el-tooltip>
              <!-- <el-tooltip content="删除" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasRole="['admin', 'student']"
                ></el-button>
              </el-tooltip> -->
              <!-- <el-tooltip
                content="提交"
                placement="top"
                v-if="
                  scope.row.approvalStatus === 'no_submit' ||
                  scope.row.approvalStatus === 'rejected'
                "
              >
                <el-button
                  link
                  type="warning"
                  icon="Upload"
                  @click="handleSubmit(scope.row)"
                  v-hasRole="['admin', 'student']"
                ></el-button>
              </el-tooltip> -->
              <el-tooltip
                content="审批"
                placement="top"
                v-if="scope.row.approvalAuth"
              >
                <el-button
                  link
                  type="success"
                  icon="Check"
                  @click="handleApprove(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleGetList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="160px" :label-position="isPhone ? 'top' : 'left'">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学生" prop="userId" label-width="50px">
              <el-select
                v-model="form.userId"
                placeholder="请选择学生"
                clearable
                :disabled="title === '查看企业实践进度详情' || true"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="formUserInfo">
            <el-col :span="12">
              <el-form-item label="学校" label-width="50px">
                <el-input
                  :value="getUniversityText(formUserInfo.trainUniversity)"
                  disabled
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="专业" label-width="50px">
                <el-input v-model="formUserInfo.trainMajor" disabled>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="培养单位" label-width="80px">
                <el-input v-model="formUserInfo.trainDeptName" disabled>
                </el-input>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="12">
            <el-form-item label="填报时间" prop="reportTime">
              <el-date-picker
                v-model="form.reportTime"
                type="date"
                placeholder="请选择填报时间"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled="title === '查看企业实践进度详情' || true"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="月度课题进展描述" prop="monthlyProgress">
              <el-input
                v-model="form.monthlyProgress"
                type="textarea"
                placeholder="请输入月度课题进展描述"
                :rows="3"
                :disabled="title === '查看企业实践进度详情'"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="月度学习情况描述" prop="monthlyStudy">
              <el-input
                v-model="form.monthlyStudy"
                type="textarea"
                placeholder="请输入月度学习情况描述"
                :rows="3"
                :disabled="title === '查看企业实践进度详情'"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="思想状态" prop="mentalState">
              <el-input
                v-model="form.mentalState"
                type="textarea"
                placeholder="请输入思想状态"
                :rows="3"
                :disabled="title === '查看企业实践进度详情'"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="月度企业导师交流次数"
              prop="enterpriseMentorCount"
            >
              <el-input-number
                v-model="form.enterpriseMentorCount"
                :min="0"
                placeholder="请输入交流次数"
                style="width: 100%"
                :disabled="title === '查看企业实践进度详情'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="月度高校导师交流次数" prop="schoolMentorCount">
              <el-input-number
                v-model="form.schoolMentorCount"
                :min="0"
                placeholder="请输入交流次数"
                style="width: 100%"
                :disabled="title === '查看企业实践进度详情'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="企业导师建议" prop="enterpriseMentorAdvice">
              <el-input
                v-model="form.enterpriseMentorAdvice"
                type="textarea"
                placeholder="请输入企业导师建议"
                :rows="3"
                :disabled="title === '查看企业实践进度详情'"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="高校导师建议" prop="schoolMentorAdvice">
              <el-input
                v-model="form.schoolMentorAdvice"
                type="textarea"
                placeholder="请输入高校导师建议"
                :rows="3"
                :disabled="title === '查看企业实践进度详情'"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="整体进展情况" prop="overallProgress">
              <el-select
                v-model="form.overallProgress"
                placeholder="请选择整体进展情况"
                clearable
                style="width: 100%"
                :disabled="title === '查看企业实践进度详情'"
              >
                <el-option
                  v-for="dict in overall_progress"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="是否有其他需解决问题/报告事项"
              prop="hasOtherIssues"
            >
              <el-radio-group v-model="form.hasOtherIssues" :disabled="title === '查看企业实践进度详情'">
                <el-radio
                  v-for="dict in sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.hasOtherIssues === 'Y'">
            <el-form-item
              label="其他需解决问题/报告事项内容"
              prop="otherIssuesContent"
            >
              <el-input
                v-model="form.otherIssuesContent"
                type="textarea"
                placeholder="请输入其他需解决问题/报告事项内容"
                :rows="3"
                :disabled="title === '查看企业实践进度详情'"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.hasOtherIssues === 'Y'">
            <el-form-item
              label="其他需解决问题/报告事项状态"
              prop="otherIssuesStatus"
            >
              <el-select
                v-model="form.otherIssuesStatus"
                placeholder="请选择问题状态"
                clearable
                style="width: 100%"
                :disabled="title === '查看企业实践进度详情'"
              >
                <el-option
                  v-for="dict in resolved_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关心关爱活动开展次数" prop="careActivityCount">
              <el-input-number
                v-model="form.careActivityCount"
                :min="0"
                placeholder="请输入活动次数"
                style="width: 100%"
                :disabled="title === '查看企业实践进度详情'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训开展次数" prop="trainingCount">
              <el-input-number
                v-model="form.trainingCount"
                :min="0"
                placeholder="请输入培训次数"
                style="width: 100%"
                :disabled="title === '查看企业实践进度详情'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="关心关爱活动内容" prop="careActivityContent">
              <el-input
                v-model="form.careActivityContent"
                type="textarea"
                placeholder="请输入关心关爱活动内容"
                :rows="3"
                :disabled="title === '查看企业实践进度详情'"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="培训课程名称" prop="trainingCourseName">
              <el-input
                v-model="form.trainingCourseName"
                placeholder="请输入培训课程名称"
                :disabled="title === '查看企业实践进度详情'"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="新增获奖数量" prop="newAwardCount">
              <el-input-number
                v-model="form.newAwardCount"
                :min="0"
                placeholder="请输入获奖数量"
                style="width: 100%"
                :disabled="title === '查看企业实践进度详情'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.newAwardCount > 0">
            <el-form-item label="获奖时间" prop="awardTime">
              <el-date-picker
                v-model="form.awardTime"
                type="date"
                placeholder="请选择获奖时间"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled="title === '查看企业实践进度详情'"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.newAwardCount > 0">
            <el-form-item label="奖项名称" prop="awardName">
              <el-input v-model="form.awardName" placeholder="请输入奖项名称" :disabled="title === '查看企业实践进度详情'">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="新增获批专利数量" prop="newPatentCount">
              <el-input-number
                v-model="form.newPatentCount"
                :min="0"
                placeholder="请输入专利数量"
                style="width: 100%"
                :disabled="title === '查看企业实践进度详情'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.newPatentCount > 0">
            <el-form-item label="获批时间" prop="patentApprovalTime">
              <el-date-picker
                v-model="form.patentApprovalTime"
                type="date"
                placeholder="请选择获批时间"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled="title === '查看企业实践进度详情'"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.newPatentCount > 0">
            <el-form-item label="专利名称" prop="patentName">
              <el-input v-model="form.patentName" placeholder="请输入专利名称" :disabled="title === '查看企业实践进度详情'">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="新完成论文数量" prop="newPaperCount">
              <el-input-number
                v-model="form.newPaperCount"
                :min="0"
                placeholder="请输入论文数量"
                style="width: 100%"
                :disabled="title === '查看企业实践进度详情'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.newPaperCount > 0">
            <el-form-item label="完成时间" prop="paperCompletionTime">
              <el-date-picker
                v-model="form.paperCompletionTime"
                type="date"
                placeholder="请选择完成时间"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled="title === '查看企业实践进度详情'"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.newPaperCount > 0">
            <el-form-item label="论文名称" prop="paperName">
              <el-input v-model="form.paperName" placeholder="请输入论文名称" :disabled="title === '查看企业实践进度详情'">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入备注信息（选填）"
                :rows="3"
                :disabled="title === '查看企业实践进度详情'"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form-item
        label="审核意见"
        prop="approvalRemark"
        style="margin-bottom: 0"
        v-if="form.approvalStatus === 'rejected'"
      >
        <el-input
          v-model="form.approvalRemark"
          disabled
          type="textarea"
          placeholder="请输入审核意见"
          :rows="3"
          style="width: 100%"
        ></el-input>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <!-- 审批模式下的审核意见字段 -->
          <div v-if="title === '审批企业实践进度'" style="margin-bottom: 20px">
            <el-form-item
              label="审核意见"
              prop="approvalRemark"
              style="margin-bottom: 0"
            >
              <el-input
                v-model="form.approvalRemark"
                type="textarea"
                placeholder="请输入审核意见"
                :rows="3"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </div>

          <!-- 普通编辑模式按钮 -->
          <template v-if="title !== '审批企业实践进度' && title !== '查看企业实践进度详情'">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button type="primary" @click="saveAndSubmit"
              >保存并提交</el-button
            >
            <el-button @click="cancel">取 消</el-button>
          </template>

          <!-- 详情模式按钮 -->
          <template v-if="title === '查看企业实践进度详情'">
            <el-button @click="cancel">关 闭</el-button>
          </template>

          <!-- 审批模式按钮 -->
          <template v-else>
            <el-button type="success" @click="handleApprovePass"
              >通 过</el-button
            >
            <el-button type="danger" @click="handleApproveReject"
              >驳 回</el-button
            >
            <el-button @click="cancel">取 消</el-button>
          </template>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EnterprisePracticeProgress">
import {
  getList,
  addItem,
  editItem,
  delItem,
  getDetail,
} from "@/api/enterprise-practice-progress";
import { submitApproval, handleApproval } from "@/api/approval";
import { getStudentList } from "@/api/common";
import moment from "moment";
import { isPhone } from "@/utils/index";
import { yearOptions } from "@/utils/constant";

const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_yes_no, university, overall_progress, resolved_status } =
  proxy.useDict(
    "sys_yes_no",
    "university",
    "overall_progress",
    "resolved_status"
  );

const list = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 列显隐信息
const columns = ref([
  { key: 0, label: `编号`, visible: true },
  { key: 1, label: `姓名`, visible: true },
  { key: 2, label: `学校`, visible: true },
  { key: 3, label: `专业`, visible: true },
  { key: 4, label: `培养单位`, visible: true },
  { key: 5, label: `入企时间`, visible: true },
  { key: 6, label: `月度计划`, visible: true },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nickName: undefined,
    trainUniversity: undefined,
    trainMajor: undefined,
    trainDeptName: undefined,
    practiceStartYear: undefined,
  },
  rules: {
    userId: [{ required: true, message: "请选择学生", trigger: "change" }],
    reportTime: [
      { required: true, message: "请选择填报时间", trigger: "change" },
    ],
    monthlyProgress: [
      { required: true, message: "请输入月度课题进展描述", trigger: "blur" },
    ],
    monthlyStudy: [
      { required: true, message: "请输入月度学习情况描述", trigger: "blur" },
    ],
    mentalState: [
      { required: true, message: "请输入思想状态", trigger: "blur" },
    ],
    enterpriseMentorCount: [
      {
        required: true,
        message: "请输入月度企业导师交流次数",
        trigger: "blur",
      },
    ],
    enterpriseMentorAdvice: [
      { required: true, message: "请输入企业导师建议", trigger: "blur" },
    ],
    schoolMentorCount: [
      {
        required: true,
        message: "请输入月度高校导师交流次数",
        trigger: "blur",
      },
    ],
    schoolMentorAdvice: [
      { required: true, message: "请输入高校导师建议", trigger: "blur" },
    ],
    overallProgress: [
      { required: true, message: "请选择整体进展情况", trigger: "change" },
    ],
    hasOtherIssues: [
      {
        required: true,
        message: "请选择是否有其他需解决问题/报告事项",
        trigger: "change",
      },
    ],
    otherIssuesContent: [
      {
        required: function () {
          return form.value.hasOtherIssues === "Y";
        },
        message: "请输入其他需解决问题/报告事项内容",
        trigger: "blur",
      },
    ],
    otherIssuesStatus: [
      {
        required: function () {
          return form.value.hasOtherIssues === "Y";
        },
        message: "请选择其他需解决问题/报告事项状态",
        trigger: "change",
      },
    ],
    careActivityCount: [
      {
        required: true,
        message: "请输入关心关爱活动开展次数",
        trigger: "blur",
      },
    ],
    careActivityContent: [
      { required: true, message: "请输入关心关爱活动内容", trigger: "blur" },
    ],
    trainingCount: [
      { required: true, message: "请输入培训开展次数", trigger: "blur" },
    ],
    trainingCourseName: [
      { required: true, message: "请输入培训课程名称", trigger: "blur" },
    ],
    newAwardCount: [
      { required: true, message: "请输入新增获奖数量", trigger: "blur" },
    ],
    awardTime: [
      { required: true, message: "请选择获奖时间", trigger: "change" },
    ],
    awardName: [{ required: true, message: "请输入奖项名称", trigger: "blur" }],
    newPatentCount: [
      { required: true, message: "请输入新增获批专利数量", trigger: "blur" },
    ],
    patentApprovalTime: [
      { required: true, message: "请选择获批时间", trigger: "change" },
    ],
    patentName: [
      { required: true, message: "请输入专利名称", trigger: "blur" },
    ],
    newPaperCount: [
      { required: true, message: "请输入新完成论文数量", trigger: "blur" },
    ],
    paperCompletionTime: [
      { required: true, message: "请选择完成时间", trigger: "change" },
    ],
    paperName: [{ required: true, message: "请输入论文名称", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

const userList = ref([]);

const formUserInfo = computed(() =>
  userList.value.find((t) => t.userId === form.value.userId)
);

/** 查询用户列表 */
function handleGetList() {
  loading.value = true;
  getList(queryParams.value).then((res) => {
    loading.value = false;
    list.value = res.rows;
    total.value = res.total;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  handleGetList();
}
function resetQuery() {
  queryParams.value.nickName = undefined;
  queryParams.value.trainUniversity = undefined;
  queryParams.value.trainMajor = undefined;
  queryParams.value.trainDeptName = undefined;
  queryParams.value.practiceStartYear = undefined;
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除编号为"' + id + '"的数据项？')
    .then(function () {
      return delItem(id);
    })
    .then(() => {
      handleGetList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/user/export",
    {
      ...queryParams.value,
    },
    `user_${new Date().getTime()}.xlsx`
  );
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    progressDetails: [],
  };
  proxy.resetForm("formRef");
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

const openIndex = ref(-1);
const selectedRow = ref(null);

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  openIndex.value = row.progressDetails.findIndex(
    (t) =>
      moment(t.planStartTime).isAfter(moment()) &&
      moment(t.planEndTime).isBefore(moment())
  );
  if (openIndex.value === -1) {
    proxy.$modal.msgError("当前没有可填报的计划，请先创建本月的计划！");
    return;
    // openIndex.value = 0;
  }
  selectedRow.value = row;
  form.value = {
    ...row.progressDetails[openIndex.value],
    userId: row.userId,
    reportTime: moment().format("YYYY-MM-DD"),
    trainUniversity: row.trainUniversity,
    trainMajor: row.trainMajor,
    trainDeptName: row.trainDeptName,
  };
  open.value = true;
  title.value = "修改企业实践进度";
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      selectedRow.value.progressDetails.splice(openIndex.value, 1, form.value);
      const submitData = {
        ...selectedRow.value,
      };

      editItem(submitData).then((response) => {
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        handleGetList();
      });
    }
  });
}

function saveAndSubmit() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      selectedRow.value.progressDetails.splice(openIndex.value, 1, form.value);
      const submitData = {
        ...selectedRow.value,
      };

      editItem(submitData).then((response) => {
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        handleGetList();

        handleSubmit(selectedRow.value);
      });
    }
  });
}

// 提交审核
function handleSubmit(row) {
  const id = row.id || ids.value;
  const item = list.value.find(item => item.id === id);
  proxy.$modal
    .confirm("是否确认提交审核？")
    .then(function () {
      return submitApproval({
        businessId: id,
        approvalTypeCode: "ent_progress_flow",
        approvalInfo: JSON.stringify(item)
      });
    })
    .then(() => {
      handleGetList();
      proxy.$modal.msgSuccess("提交成功");
    })
    .catch(() => {});
}

// 审批操作
function handleApprove(row) {
  reset();
  const id = row.id || ids.value;
  getDetail(id).then((response) => {
    form.value = {
      ...response.data,
      approvalRemark: "",
    };
    open.value = true;
    title.value = "审批企业实践进度";
  });
}

// 通过审批
function handleApprovePass() {
  const approvalData = {
    approvalInfoId: form.value.approvalInfoId,
    approvalNodeId: form.value.approvalNodeId,
    approvalStatus: "approved",
    remark: form.value.approvalRemark,
  };

  handleApproval(approvalData).then(() => {
    proxy.$modal.msgSuccess("审批通过");
    open.value = false;
    handleGetList();
  });
}

// 驳回审批
function handleApproveReject() {
  if (!form.value.approvalRemark) {
    proxy.$modal.msgError("请填写审核意见");
    return;
  }

  const approvalData = {
    approvalInfoId: form.value.approvalInfoId,
    approvalNodeId: form.value.approvalNodeId,
    approvalStatus: "rejected",
    remark: form.value.approvalRemark,
  };

  handleApproval(approvalData).then(() => {
    proxy.$modal.msgSuccess("已驳回");
    open.value = false;
    handleGetList();
  });
}

// 高校名称文本显示函数
const getUniversityText = (universityValue) => {
  if (!universityValue) return "未知";
  const dict = university.value?.find((item) => item.value === universityValue);
  return dict ? dict.label : universityValue;
};

// 详情操作
function handleDetail(row) {
  reset();
  const id = row.id || ids.value;
  getDetail(id).then((response) => {
    form.value = {
      ...response.data,
      reportTime: moment().format("YYYY-MM-DD"),
      trainUniversity: row.trainUniversity,
      trainMajor: row.trainMajor,
      trainDeptName: row.trainDeptName,
    };
    open.value = true;
    title.value = "查看企业实践进度详情";
  });
}

handleGetList();
getStudentList({ roleKey: "student" }).then((res) => {
  userList.value = res.data;
});
</script>
